import { Injectable } from '@nestjs/common';
import { zip } from 'compressing';
import * as fs from 'fs';
import { ConfigService } from '@nestjs/config';
import { QiniuService } from 'src/component/qiniu/qiniu.service';
import { ToolsService } from 'src/utils/tools.service';

@Injectable()
export class UploadService {
  constructor(
    private readonly configService: ConfigService,
    private readonly qiniuService: QiniuService,
  ) {}

  async upload(file, namespace) {
    console.log('file', file);
    try {
      const url = await this.qiniuService.uploadToQiniu(file, namespace);
      await fs.unlinkSync(file.path);
      return url;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async downloadAll() {
    try {
      const uploadDir = this.configService.get('file').root;
      const tarStream = new zip.Stream(); //文件压缩流
      await tarStream.addEntry(uploadDir); //压缩文件路径
      return { filename: `${new Date().getTime()}.zip`, tarStream };
    } catch (error) {
      ToolsService.fail(error);
    }
  }
}
